import pandas as pd
import pylab as plt
import seaborn as sns
import detect_GMM
import detect_dtw
import detect_segment
import detect_dp
import detect_drawtraj
import detect_utils
import detect_dbscan
color=['red','orange','yellow','green','cyan','blue','purple','pink','c','black','brown','crimson']

path = 'E:\\Desktop\\zs\\csv\\sepdata.csv'
data = pd.read_csv(path)
data["traj_segment"] = 0
shipdata = detect_segment.traj_segment(data)  ##先对原始数据进行轨迹分段
data = detect_dp.dp(shipdata) ##对分段后的轨迹进行轨迹点压缩
print(data)
detect_drawtraj.drawtraj_df(data) ##绘制轨迹图

MMSIDATA=data['mmsi']
SHIPSMMSI = list(set(MMSIDATA))
shipcount=len(SHIPSMMSI)
trajlist = list() ##用列表存放每个轨迹段
for i in range(shipcount):
    mmsi = SHIPSMMSI[i]
    mmsi = SHIPSMMSI[i]
    ONESHIP = data.iloc[:, :][data[data.T.index[0]] == mmsi] #找出这艘船
    TRAJ_SEGMENT = list(set(ONESHIP["traj_segment"])) #这艘船轨迹段的set集合 [0,1,2,3]
    trajcount = len(TRAJ_SEGMENT) #这艘船轨迹段的数量 4
    for j in (TRAJ_SEGMENT):
        ONETRAJ = ONESHIP.iloc[:, :][ONESHIP[ONESHIP.T.index[6]] == j]
        trajlist.append(detect_utils.dftolist(ONETRAJ))
print(trajlist)
print("************************************************************")
# for i in range(len(trajlist)):
#     for j in range(i+1,len(trajlist)):
#         print(trajlist[i][0][0],"船舶的第",trajlist[i][0][6],"条轨迹和",trajlist[j][0][0],"船舶的第",trajlist[j][0][6],"条轨迹的差距为：",round(detect_dtw.dtw(trajlist[i],trajlist[j]),1))
    #3days
eps = 2.5
min_Pts = 3

    #4ships
# eps = 8
# min_Pts = 2
finaldata = detect_dbscan.DBSCAN(trajlist,eps,min_Pts)
print(finaldata)

cluster_set = set(finaldata['cluster_id'])
cluster_set.remove(-1)
for clusterid in range(len(cluster_set)):
    ONECLUSTER = finaldata.iloc[:, :][finaldata[finaldata.T.index[7]] == clusterid]  # 对于这条轨迹
    MMSIDATA = ONECLUSTER['mmsi']
    SHIPSMMSI = list(set(MMSIDATA))
    shipcount = len(SHIPSMMSI)
    trajlist = list()  ##用列表存放每个轨迹段
    x_axis_data = []
    y_axis_data = []
    for i in range(shipcount):
        mmsi = SHIPSMMSI[i]
        ONESHIP = ONECLUSTER.iloc[:, :][ONECLUSTER[ONECLUSTER.T.index[0]] == mmsi]  # 找出这艘船
        TRAJ_SEGMENT = list(set(ONESHIP["traj_segment"]))  # 这艘船轨迹段的set集合 [0,1,2,3]
        trajcount = len(TRAJ_SEGMENT)  # 这艘船轨迹段的数量 4
        for j in (TRAJ_SEGMENT):
            ONETRAJ = ONESHIP.iloc[:, :][ONESHIP[ONESHIP.T.index[6]] == j]
            # print(ONETRAJ)
            # print("************************************************************")
            x = ONETRAJ['longitude']
            y = ONETRAJ['latitude']
            plt.plot(x, y, linewidth=0.5,color = color[clusterid])
    detect_GMM.GMM_xy(ONECLUSTER)
    plt.show()
print("簇的个数为：",len(cluster_set))